package com.fsoft.core.framework;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;

public class MapRowsMapper<T> implements ResultSetExtractor<List<T>> {

	public MapRowsMapper() {
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<T> extractData(ResultSet rs) throws SQLException, DataAccessException {
		List<LinkedHashMap<String, Object>> list = new ArrayList<LinkedHashMap<String, Object>>();
		try {
			while (rs.next()) {
				LinkedHashMap<String, Object> tmp = new LinkedHashMap<String, Object>();
				ResultSetMetaData rsmd = rs.getMetaData();
				int columnCount = rsmd.getColumnCount();
				for (int i = 1; i <= columnCount; i++) {
					String column = rsmd.getColumnName(i);
					Object value = rs.getString(i);
					tmp.put(column, value);
				}
				list.add(tmp);
			}
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		}
		return (List<T>) list;
	}
}
